import requests
import pymysql
import pandas as pd
import json
import threadpool
import re
import time
import parsel
import datetime

newtime = time.strftime('%Y-%m-%d')


class Load:
    def __init__(self):
        self.conn = pymysql.connect(host='192.168.2.205', port=3306, user='jinhuitao', password='jinhuitao_123456',
                                    database='sunway_db', charset='utf8')
        self.cursor = self.conn.cursor()

        self.list1 = []

    def mysql_guolv_save(self, Tracking_number):  # 将已签收的跟踪号放到该处
        conn = pymysql.connect(host='192.168.2.205', port=3306, user='jinhuitao', password='jinhuitao_123456',
                               database='sunway_db', charset='utf8')
        cursor = conn.cursor()
        newtime = time.strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute(
            "REPLACE into load_guolv set newtime=%s,Tracking_number=%s",
            [newtime, Tracking_number])

        conn.commit()

    def mysql_guolv_to(self):  # 过滤掉已签收的跟踪号
        datas = "select Tracking_number from load_guolv"
        a = pd.read_sql(datas, self.conn)
        return a['Tracking_number']

    def mysql_(self, Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping, Delivery_method,
               Tracking_number, estimated_sailing_time, Release_time, Departure_time, Arrival_time_,
               Customs_clearance_time, Arrival_time, Extraction_time, Signing_time, Sign_in, Latest_logistics_track,
               Latest_logistics_time, Shipment_status, remarks, gold):
        conn = pymysql.connect(host='192.168.2.205', port=3306, user='jinhuitao', password='jinhuitao_123456',
                               database='sunway_db', charset='utf8')
        cursor = conn.cursor()
        newtime = time.strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute(
            "REPLACE into load_fa set newtime=%s,Delivery_time=%s,FBA_ID=%s,destination=%s,Platform_account=%s,type_of_shipping=%s,Delivery_method=%s,Tracking_number=%s,estimated_sailing_time=%s,Release_time=%s,Departure_time=%s,Arrival_time_=%s,Customs_clearance_time=%s,Arrival_time=%s,Extraction_time=%s,Signing_time=%s,Sign_in=%s,Latest_logistics_track=%s,Latest_logistics_time=%s,Shipment_status=%s,remarks=%s,gold=%s",
            [newtime, Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping, Delivery_method,
             Tracking_number, estimated_sailing_time, Release_time, Departure_time, Arrival_time_,
             Customs_clearance_time, Arrival_time, Extraction_time, Signing_time, Sign_in, Latest_logistics_track,
             Latest_logistics_time, Shipment_status, remarks, gold])

        conn.commit()

    def mysql_one(self, isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujian,
                  remark,
                  mysql_name):  # 四个参数的mysql
        conn = pymysql.connect(host='192.168.2.205', port=3306, user='jinhuitao', password='jinhuitao_123456',
                               database='sunway_db', charset='utf8')
        cursor = conn.cursor()
        newtime = time.strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute(
            "REPLACE into {} set newtime=%s,isok=%s,Primary_key=%s,times=%s,title=%s,describes=%s,Tracking_number=%s,warehouse_sku=%s,zhujian=%s,remark=%s".format(
                mysql_name),
            [newtime, isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujian,
             remark])

        conn.commit()

    def mysql_two(self, isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, pIds, zhujian,
                  remark, mysql_name):  # 五个参数的MySQL
        conn = pymysql.connect(host='192.168.2.205', port=3306, user='jinhuitao', password='jinhuitao_123456',
                               database='sunway_db', charset='utf8')
        cursor = conn.cursor()
        newtime = time.strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute(
            "REPLACE into {} set newtime=%s,isok=%s,Primary_key=%s,times=%s,title=%s,describes=%s,Tracking_number=%s,warehouse_sku=%s,pIds=%s,zhujian=%s,remark=%s".format(
                mysql_name),
            [newtime, isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, pIds, zhujian,
             remark])

        conn.commit()

    def mysql_three(self, isok, Primary_key, times, title, Tracking_number, warehouse_sku, zhujian, remark,
                    mysql_name):  # 三个参数的MySQL
        newtime = time.strftime('%Y-%m-%d %H:%M:%S')
        conn = pymysql.connect(host='192.168.2.205', port=3306, user='jinhuitao', password='jinhuitao_123456',
                               database='sunway_db', charset='utf8')
        cursor = conn.cursor()
        cursor.execute(
            "REPLACE into {} set newtime=%s,isok=%s,Primary_key=%s,times=%s,title=%s,Tracking_number=%s,warehouse_sku=%s,zhujian=%s,remark=%s".format(
                mysql_name),
            [newtime, isok, Primary_key, times, title, Tracking_number, warehouse_sku, zhujian, remark])

        conn.commit()

    def return_mysql(self):  # 获取数据库中的跟踪号和运输方式
        datas = "select user_account,fbaid,actual_deliver_time,track_code,logistics_method,warehouse_sku,zhujian,fba_status from det_fba_first_shipment_product"
        a = pd.read_sql(datas, self.conn)
        track_code_all = a['track_code']  # 跟踪号
        logistics_method_all = a['logistics_method']  # 运输方式
        warehouse_sku_all = a['warehouse_sku']  # 仓库sku
        zhujian_all = a['zhujian']  # 主键
        fba_status = a['fba_status']  # 状态
        actual_deliver_time = a['actual_deliver_time']  # 发货时间
        fbaid = a['fbaid']  # FBA ID
        # 目的地
        user_account = a['user_account']  # 平台帐号
        list_all = []
        list_all_ = []
        guolv = self.mysql_guolv_to()
        for jj in range(len(track_code_all)):
            if str(track_code_all[jj]) != 'None' and track_code_all[jj] not in list_all_ and track_code_all[
                jj] not in guolv:
                list_all_.append(track_code_all[jj])
                all = str(track_code_all[jj]) + '我是你哥' + str(logistics_method_all[jj]) + '我是你哥' + str(
                    warehouse_sku_all[jj]) + '我是你哥' + str(zhujian_all[jj]) + '我是你哥' + str(
                    fba_status[jj]) + '我是你哥' + str(actual_deliver_time[jj]) + '我是你哥' + str(fbaid[jj]) + '我是你哥' + str(
                    user_account[jj])
                list_all.append(all)
        return list_all

    def screening_load(self):  # 甄别物流方式  主函数
        list_ = self.return_mysql()
        # for i in list_:
        #     self.threading_thread(i)

        task_pool = threadpool.ThreadPool(10)
        requests = threadpool.makeRequests(self.threading_thread, list_)
        for req in requests:
            task_pool.putRequest(req)
        task_pool.wait()

    def threading_thread(self, word):
        # for word in self.return_mysql():
        #     print(word)
        words = word.split('我是你哥')
        load = words[1]  # 运输方式
        load_show = words[0]  # 跟踪号
        load_sku = words[2]  # 仓库sku
        zhujian = words[3]  # 主键
        fba_status = words[4]  # 状态
        actual_deliver_time = words[5]  # 发货时间
        fbaid = words[6]  # fbaid
        user_account = words[7]  # 平台账号
        Delivery_method = '快递' if '快递' in load else '空派' if '空派' in load else '海快' if '海快' in load else ''
        if fba_status not in ['-1']:
            if load in ['TC-MY[明扬UPS-快递]', 'TC-FD-HK[飞点海快]', 'TC-ZUOZI-MS-HK[卓志美森海快]', 'TC-PMS-HK[派敏斯美森海快]',
                        'TC-YP-HK[易派-海快]']:
                pass
                # time.sleep(3)
                # try:
                # self.ups(actual_deliver_time, fbaid, user_account, load, Delivery_method, load_show, load_sku,
                #              zhujian)
                # except Exception as g:
                #     times, title, describes, Tracking_number, warehouse_sku, zhujians, remark = '', '', '', load_show, load_sku, zhujian, '无数据'
                #
                #     Primary_key = zhujian + str(times) + title
                #     isok = None
                #     print('ups', times, title, describes, Tracking_number, warehouse_sku, zhujians, remark)
                #     self.mysql_one(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                #                    remark,
                #                    mysql_name='load_ups')
                #     Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping, \
                #     Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time, \
                #     Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time, Sign_in, \
                #     Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold = actual_deliver_time, fbaid, '', user_account, load, Delivery_method, load_show, None, None, None, None, None, None, None, None, '', '', None, '', '', zhujian
                #
                #     self.mysql_(Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping,
                #                 Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time,
                #                 Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time,
                #                 Sign_in,
                #                 Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)

            elif load in ['TC-FS-FEDEX[拓派佛山FedEx-快递]']:
                pass
                # try:
                #     self.fedex(actual_deliver_time, fbaid, user_account, load, Delivery_method, load_show, load_sku,
                #                zhujian)
                # except Exception as g:
                #     times, title, describes, Tracking_number, warehouse_sku, zhujians, remark = '', '', '', load_show, load_sku, zhujian, '无数据'
                #     Primary_key = zhujian + str(times) + title
                #     isok = None
                #     print('fedex', times, title, describes, Tracking_number, warehouse_sku, zhujians, remark)
                #     self.mysql_one(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                #                    remark,
                #                    mysql_name='load_fedex')
                #
                #     Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping, \
                #     Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time, \
                #     Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time, Sign_in, \
                #     Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold = actual_deliver_time, fbaid, '', user_account, load, Delivery_method, load_show, None, None, None, None, None, None, None, None, '', '', None, '', '', zhujian
                #
                #     self.mysql_(Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping,
                #                 Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time,
                #                 Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time,
                #                 Sign_in,
                #                 Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)



            elif load in ['TC-YFH-DHL[原飞航DHL快递]', 'TC-HJ-DHL[宏久DHL-快递]', 'TC-SD-DHL[烁达DHL 快递]']:
                # pass
                try:
                    time.sleep(1)
                    self.dhl(actual_deliver_time, fbaid, user_account, load, Delivery_method, load_show, load_sku,
                             zhujian)
                except Exception as g:
                    times, title, describes, Tracking_number, warehouse_sku, pIds, zhujians, remark = '', '', '', load_show, load_sku, '', zhujian, '无数据'
                    Primary_key = zhujian + str(times) + title
                    isok = None
                    print('dhl', times, title, describes, Tracking_number, pIds, zhujians, remark)
                    self.mysql_two(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, pIds,
                                   zhujians, remark,
                                   mysql_name='load_dhl')

                    Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping, \
                    Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time, \
                    Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time, Sign_in, \
                    Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold = actual_deliver_time, fbaid, '', user_account, load, Delivery_method, load_show, None, None, None, None, None, None, None, None, '', '', None, '', '', zhujian

                    self.mysql_(Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping,
                                Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time,
                                Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time,
                                Sign_in,
                                Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)



            elif load in ['TC-JF-KP[九方-空派]']:
                pass
                # try:
                # self.jiufang(actual_deliver_time, fbaid, user_account, load, Delivery_method, load_show, load_sku,
                #              zhujian)
            # except Exception as g:
            #     times, title, Tracking_number, warehouse_sku, zhujians, remark = '', '', load_show, load_sku, zhujian, '无数据'
            #     Primary_key = zhujian + str(times) + title
            #     isok = None
            #     print('九方', times, title, Tracking_number, warehouse_sku, zhujians, remark)
            #     self.mysql_three(isok, Primary_key, times, title, Tracking_number, warehouse_sku, zhujians, remark,
            #                      mysql_name='load_jiufang')
            #
            #     Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping, \
            #     Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time, \
            #     Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time, Sign_in, \
            #     Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold = actual_deliver_time, fbaid, '', user_account, load, Delivery_method, load_show, None, None, None, None, None, None, None, None, '', '', None, '', '', zhujian
            #
            #     self.mysql_(Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping,
            #                 Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time,
            #                 Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time,
            #                 Sign_in,
            #                 Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)

            elif load in ['TC-MT-KP[深圳美通-空派]']:
                pass
                # try:
                #     self.aff_1(actual_deliver_time, fbaid, user_account, load, Delivery_method, load_show, load_sku,
                #                zhujian)
                # except Exception as g:
                #     times, title, describes, Tracking_number, warehouse_sku, zhujians, remark = '', '', '', load_show, load_sku, zhujian, '无数据'
                #     Primary_key = zhujian + str(times) + title
                #     isok = None
                #     print('aff', times, title, describes, Tracking_number, warehouse_sku, zhujians,
                #           remark)
                #     self.mysql_one(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                #                    remark, mysql_name='load_aff')
                #
                #     Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping, \
                #     Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time, \
                #     Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time, Sign_in, \
                #     Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold = actual_deliver_time, fbaid, '', user_account, load, Delivery_method, load_show, None, None, None, None, None, None, None, None, '', '', None, '', '', zhujian
                #
                #     self.mysql_(Delivery_time, FBA_ID, destination, Platform_account, type_of_shipping,
                #                 Delivery_method, Tracking_number, estimated_sailing_time, Release_time, Departure_time,
                #                 Arrival_time_, Customs_clearance_time, Arrival_time, Extraction_time, Signing_time,
                #                 Sign_in,
                #                 Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)


            else:
                print()


        else:
            print('iiii')

    def aff(self, load_show):
        cookie_Token_ = self.login_1()
        url = 'http://aafgzx.nextsls.com/wos/shipment/index?kw={}&waybill_number=&service=&daterange=&created_daterange=&country=&name=&store_id='.format(
            load_show)
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'Connection': 'keep-alive',
            'Cookie': '{}'.format(cookie_Token_[1]),
            'Host': 'aafgzx.nextsls.com',
            'Referer': 'http://aafgzx.nextsls.com/wos/shipment/index?status=picked',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',

        }

        response = requests.get(url, headers=headers).text
        response_parsel = parsel.Selector(response)
        response_parsel_country = response_parsel.css(
            '#w0 > table > tbody > tr > td:nth-child(5)::text').extract_first()
        response_tbody = re.findall('<tbody>(.*?)</tbody>', response, re.S)[0]
        response_data_key = re.findall('data-key="(.*?)"', response_tbody)[0]
        return [cookie_Token_[0], cookie_Token_[1], response_data_key, response_parsel_country]

    def aff_1(self, actual_deliver_time, fbaid, user_account, load, Delivery_method, load_show, load_sku, zhujian):
        times1 = int(time.time() * 1000)
        id_cookie_token = self.aff(load_show)
        url = 'http://aafgzx.nextsls.com/wos/shipment/show_traces?id={}&lmodal=1&_={}'.format(
            id_cookie_token[2], times1)
        headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'Connection': 'keep-alive',
            'Cookie': '{}'.format(id_cookie_token[1]),
            'Host': 'aafgzx.nextsls.com',
            'Referer': 'http://aafgzx.nextsls.com/wos/shipment/index?status=delivered',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
            'X-CSRF-Token': '{}'.format(id_cookie_token[0]),
            'X-Requested-With': 'XMLHttpRequest',
        }
        param = {
            'id': '{}'.format(id_cookie_token[2]),
            'lmodal': '1',
            '_': '{}'.format(times1)

        }
        response = requests.get(url, headers=headers, params=param).text
        response_parsel = parsel.Selector(response)
        response_parsel_ = response_parsel.css('#one-column > div')
        is_ok = True
        country = id_cookie_token[3]
        dict_ups = {'DELIVERED': None, '航班已抵达': None, '航班已起飞': None, '已下单': None, '货物已交付': None, '已清关放行': None,
                    '已发出': None}
        Tracking_number = load_show
        Sign_in = '否'
        Shipment_status = '正常'
        Shipment_status_ = True

        for response_parsel_div in response_parsel_:
            response_parsel_div_ = response_parsel_div.css('div > div.message-head.clearfix::text').get().strip()  # 时间
            response_parsel_div_span = response_parsel_div.css(
                'div > div.qa-message-content span::text').get().strip()  # 标题
            print(id_cookie_token[3], response_parsel_div_, response_parsel_div_span)
            times, title, describes, Tracking_number, warehouse_sku, zhujians, remark = response_parsel_div_, response_parsel_div_span, \
                                                                                        id_cookie_token[
                                                                                            3], load_show, load_sku, zhujian, ''

            ######获取节点时间和判断物流时间是否异常
            if 'DELIVERED' in title or title == '已签收':
                dict_Signing_time = {'DELIVERED': response_parsel_div_}
                Sign_in = '是'
                Shipment_status_ = False
                self.mysql_guolv_save(Tracking_number)

                dict_ups.update(dict_Signing_time)
            elif '航班已抵达' in title:
                dict_Customs_clearance_time = {'航班已抵达': response_parsel_div_}
                dict_ups.update(dict_Customs_clearance_time)
            elif '航班已起飞' in title:
                dict_estimated_sailing_time = {'航班已起飞': response_parsel_div_}
                dict_ups.update(dict_estimated_sailing_time)
            elif title == '已下单':
                dict_estimated_sailing_time = {'已下单': response_parsel_div_}
                dict_ups.update(dict_estimated_sailing_time)
            elif '货物已交付' in title:
                dict_estimated_sailing_time = {'货物已交付': response_parsel_div_}
                dict_ups.update(dict_estimated_sailing_time)
            elif '已清关放行' in title:
                dict_estimated_sailing_time = {'已清关放行': response_parsel_div_}
                dict_ups.update(dict_estimated_sailing_time)
            elif '已发出' in title:
                dict_estimated_sailing_time = {'已发出': response_parsel_div_}
                dict_ups.update(dict_estimated_sailing_time)

            Primary_key = zhujians + str(times) + title
            data_ = response_parsel_div_span.split('，')[0]
            if is_ok and ('航班已抵达' in data_ or 'DELIVERED' in data_ or '航班已起飞' in data_ or '已下单' in data_ or
                          '货物已交付' in data_ or '已清关放行' in data_ or '已发出' in data_):
                isok = self.times_(title.split('，')[0], 'aff', times)  # 计算预计到达时间
                self.mysql_one(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                               remark,
                               mysql_name='load_aff')
                is_ok = False
                print('aff:::', isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                      remark)
            else:
                isok_ = None
                self.mysql_one(isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                               remark,
                               mysql_name='load_aff')
                print('aff:::', isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                      remark)

        #####判断物流时间是否异常
        new = str(datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(
            response_parsel.css(
                '#one-column > div:nth-child(1) > div > div.message-head.clearfix::text').get().strip().split(' ')[0],
            '%Y-%m-%d'))
        new_ = int(re.sub('[^0-9]', '', new.split(', ')[0]))
        if Shipment_status_ and new_ > 4:
            Shipment_status = '异常'
        # Release_time = None
        # Departure_time = None
        # Arrival_time_ = None
        # Arrival_time = None
        Extraction_time = None
        Latest_logistics_track, Latest_logistics_time, remarks, gold = \
            response_parsel.css('#one-column > div:nth-child(1) > div > div.qa-message-content > span::text').get(), \
            response_parsel.css(
                '#one-column > div:nth-child(1) > div > div.message-head.clearfix::text').get().strip().split(' ')[0] \
                , '', zhujian
        self.mysql_(actual_deliver_time, fbaid, country, user_account, load,
                    Delivery_method, Tracking_number, dict_ups['已发出'],
                    dict_ups['已发出'],
                    dict_ups['航班已起飞'],
                    dict_ups['航班已抵达'], dict_ups['已清关放行'], dict_ups['货物已交付'], Extraction_time, dict_ups['DELIVERED'],
                    Sign_in,
                    Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)

    def login_(self):
        url = 'http://aafgzx.nextsls.com/wos/login/'
        headers = {

            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Cookie': 'grid-view-pagesize=10',
            'Host': 'aafgzx.nextsls.com',
            'Referer': 'http://aafgzx.nextsls.com/wos/login/',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',

        }
        response = requests.get(url, headers=headers)
        return [response.headers['Set-Cookie'], re.findall('<meta name="csrf-token" content="(.*)">', response.text)[0]]

    def login_1(self):
        cookie_Token = self.login_()
        url = 'http://aafgzx.nextsls.com/wos/login'
        headers = {

            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie': '{}'.format(cookie_Token[0]),
            'Host': 'aafgzx.nextsls.com',
            'Origin': 'http://aafgzx.nextsls.com',
            'Referer': 'http://aafgzx.nextsls.com/wos/login/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
            'X-CSRF-Token': '{}'.format(cookie_Token[1]),
            'X-Requested-With': 'XMLHttpRequest',

        }

        data = {
            'username': '广州盛业',
            'password': '123456',
            'inajax': '1'
        }
        response = requests.post(url, headers=headers, data=data).headers
        cookie = '_csrf-parcelos-wos' + re.findall('_csrf-parcelos-wos(.*?);', cookie_Token[0])[
            0] + ';' + 'parcelos_wos=' + \
                 re.findall('parcelos_wos=(.*?);', response['Set-Cookie'])[0]
        return [cookie_Token[1], cookie]

    def jiufang(self, actual_deliver_time, fbaid, user_account, load, Delivery_method, jiufang_load, warehouse_sku,
                zhujians):
        url = 'http://www.tofba.com:8081/seaair/waybills/listPage'
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'Authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJyZWdpc3RlcmVkTW9iaWxlUGhvbmVOdW1iZXIiOiIxODAyODU2OTY0MCIsInN1YiI6IjM4NzgiLCJjdXN0b21lckxvZ2luTmFtZSI6IlNXRFpTVyIsImlzcyI6ImF1dGhvciIsImN1c3RvbWVyQ29kZSI6Iko0MjQ1IiwiaWQiOjM4NzgsImV4cCI6MTYyMTg0MzY0NiwiaWF0IjoxNjIxODQzNjQ2LCJqdGkiOiIyY2VjOTYwMC0yODI4LTRiMmQtODRmZS0yYTE1MTk2YjQwOTEiLCJjdXN0b21lck5hbWVTaG9ydCI6Iuebm-S4uueUteWtkOWVhuWKoSJ9.D4BRKMUuV5bf6JS6dkydn1-9Z0CjbOUbqppqhMviA8E',
            'Cache-Control': 'no-cache',
            'Content-Length': '209',
            'Content-Type': 'application/json; charset=UTF-8',
            'Host': 'www.tofba.com:8081',
            'Origin': 'http://tofba.com:8887',
            'Pragma': 'no-cache',
            'Proxy-Connection': 'keep-alive',
            'Referer': 'http://tofba.com:8887/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
            'x-tofba-session-status': 'y',
        }
        parm = json.dumps(
            {"status": [0], "inStockChannel": "", "waybillNo": "{}".format(jiufang_load), "trackNumber": "",
             "referenceNo": "",
             "countryId": "", "declareNameCn": "", "sku": "", "dispatchAddressCode": "", "shipmentID": "",
             "pageSize": 20, "currentPage": 1})
        parm1 = json.dumps(
            {"status": [0], "inStockChannel": "", "waybillNo": "", "trackNumber": "",
             "referenceNo": "",
             "countryId": "", "declareNameCn": "", "sku": "", "dispatchAddressCode": "",
             "shipmentID": "{}".format(jiufang_load),
             "pageSize": 20, "currentPage": 1})
        # if jiufang_load[:2] == 'ZX':
        # try:
        #     res = requests.post(url, headers=headers, data=parm, timeout=10).json()
        #     id = res['datas'][0]['id']
        #     # self.jiufang_id(id)
        #     self.jiufang_run(actual_deliver_time, fbaid, user_account, load, Delivery_method, jiufang_load, id,
        #                      warehouse_sku, zhujians)
        # # else:
        # except Exception as g:
        res = requests.post(url, headers=headers, data=parm, timeout=10).json()
        ids = str(res['count'])

        if ids == '0':
            res1 = requests.post(url, headers=headers, data=parm1, timeout=10).json()

            try:
                print(jiufang_load)
                id1 = res1['datas'][0]['id']

                self.jiufang_run(actual_deliver_time, fbaid, user_account, load, Delivery_method, jiufang_load, id1,
                                 warehouse_sku, zhujians)
            except IndexError as g:
                # print(jiufang_load)

                times, title, remark = '', '', '无数据'
                Primary_key = zhujians + str(times) + title
                isok = None
                print('九方', times, title, jiufang_load, warehouse_sku, zhujians, remark)
                self.mysql_three(isok, Primary_key, times, title, jiufang_load, warehouse_sku, zhujians, remark,
                                 mysql_name='load_jiufang')
        else:
            id = res['datas'][0]['id']
            self.jiufang_run(actual_deliver_time, fbaid, user_account, load, Delivery_method, jiufang_load, id,
                             warehouse_sku, zhujians)

    def jiufang_run(self, actual_deliver_time, fbaid, user_account, load, Delivery_method, jiufang_load, id,
                    warehouse_sku, zhujians):

        jim = {
            '329': '美国',
            '330': '英国',
            '331': '德国',
            '332': '加拿大',
            '333': '日本',
            '334': '西班牙',
            '335': '法国',
            '336': '意大利',
            '337': '中国',
            '338': '奥地利',
            '339': '澳大利亚',
            '340': '瑞士',
            '341': '埃及',
            '342': '芬兰',
            '343': '印度',
            '344': '爱尔兰',
            '345': '印度尼西亚',
            '346': '柬埔寨',
            '347': '韩国',
            '348': '墨西哥',
            '349': '荷兰',
            '350': '挪威',
            '351': '缅甸',
            '352': '菲律宾',
            '353': '比利时',
            '354': '圭亚那',
            '355': '瑞典',
            '356': '巴拉圭',
            '357': '乌克兰',
            '358': '秘鲁',
            '359': '阿联酋',
            '360': '越南',
            '361': '索马里',
            '362': '老挝',
            '363': '科威特',
            '364': '马来西亚',
            '365': '丹麦',
            '366': '巴基斯坦',
            '367': '泰国',
            '368': '匈牙利',
            '369': '拉脱维亚',
            '370': '俄罗斯',
            '371': '捷克',
            '372': '波兰',
            '373': '白俄罗斯',
            '374': '立陶宛',
            '375': '卢森堡',
            '376': '安道尔',
            '377': '安提瓜',
            '378': '罗马尼亚',
            '379': '亚美尼亚',
            '380': '佛得角',
            '381': '阿尔及利亚',
            '382': '罗塔岛（北马里亚纳群岛）',
            '383': '东帝汶',
            '384': '毛里求斯',
            '385': '赞比亚',
            '386': '圣巴泰勒米',
            '387': '圣马丁（瓜德罗普岛）',
            '388': '巴林',
            '389': '冈比亚',
            '390': '马尔代夫',
            '391': '库克群岛',
            '392': '留尼汪岛',
            '393': '伊拉克',
            '394': '格林纳达',
            '395': '密克罗尼西亚',
            '396': '委内瑞拉',
            '397': '新喀里多尼亚',
            '398': '尼泊尔',
            '399': '摩尔多瓦共和国',
            '400': '梵蒂冈',
            '401': '瓜德罗普岛',
            '402': '关岛',
            '403': '纳米比亚',
            '404': '卡塔尔',
            '405': '马约特岛岛',
            '406': '黑山',
            '407': '不丹',
            '408': '乌兹别克斯坦',
            '409': '瓦利斯群岛和富图纳群岛',
            '410': '约旦',
            '411': '马其顿',
            '412': '布基纳法索',
            '413': '尼日尔',
            '414': '威尔士(英国)',
            '415': '格鲁吉亚',
            '416': '冰岛',
            '417': '厄立特里亚',
            '418': '科摩罗',
            '419': '塞内加尔',
            '420': '爱沙尼亚',
            '421': '中国澳门',
            '422': '斯洛文尼亚',
            '423': '乌干达',
            '424': '津巴布韦',
            '425': '乍得',
            '426': '格陵兰岛',
            '427': '阿富汗',
            '428': '刚果人民共和国',
            '429': '蒙古',
            '430': '毛里塔尼亚',
            '431': '哥伦比亚',
            '432': '特立尼达和多巴哥',
            '433': '苏格兰',
            '434': '中非共和国',
            '435': '直布罗陀',
            '436': '开曼群岛',
            '437': '尼加拉瓜',
            '438': '多哥',
            '439': '赤道几内亚',
            '440': '圣基茨',
            '441': '托尔托拉岛（英属处女岛）',
            '442': '坦桑尼亚共和国',
            '443': '肯尼亚',
            '444': '马绍尔群岛',
            '445': '哈萨克斯坦',
            '446': '沙特阿拉伯',
            '447': '文莱',
            '448': '叙利亚',
            '449': '洪都拉斯',
            '450': '巴布亚新几内亚',
            '452': '海地',
            '453': '圣马力诺',
            '454': '马拉维',
            '455': '喀麦隆',
            '456': '马达加斯加',
            '457': '葡萄牙',
            '458': '哥斯达黎加',
            '459': '百慕大',
            '460': '苏里南',
            '461': '所罗门群岛',
            '462': '大溪地',
            '463': '库拉索',
            '464': '中国台湾',
            '465': '塞拉里昂',
            '466': '特鲁克岛(密克罗尼西亚联邦)',
            '467': '联盟群岛(圣文森特和格林纳丁斯群岛)',
            '468': '圣托马斯(美属维尔京群岛)',
            '469': '诺福克',
            '470': '危地马拉',
            '471': '保加利亚',
            '472': '波纳佩岛（密克罗尼西亚联邦）',
            '473': '阿鲁巴岛',
            '474': '厄瓜多尔',
            '475': '塞尔维亚',
            '476': '巴哈马',
            '477': '玻利维亚',
            '478': '帕劳',
            '479': '吉尔吉斯斯坦',
            '480': '特克斯和凯科斯群岛',
            '481': '圣卢西亚',
            '482': '阿塞拜疆',
            '483': '马耳他',
            '484': '布隆迪',
            '485': '安哥拉',
            '486': '塞浦路斯',
            '487': '巴西',
            '488': '西萨摩亚',
            '489': '奥兰群岛',
            '490': '利比里亚',
            '491': '法罗群岛',
            '492': '圣约翰(美属维尔京群岛)',
            '493': '新加坡',
            '494': '尼日利亚',
            '495': '巴拿马',
            '496': '吉布提',
            '497': '斯威士兰',
            '498': '多米尼加共和国',
            '499': '摩斯雷（密克罗尼西亚联邦）',
            '500': '莫桑比克',
            '501': '美国萨摩亚群岛',
            '502': '乌拉圭',
            '503': '科特迪瓦共和国',
            '504': '阿尔巴尼亚',
            '505': '刚果',
            '506': '安圭拉',
            '507': '卢旺达',
            '508': '希腊',
            '509': '博茨瓦纳',
            '510': '克罗地亚',
            '511': '塞舌尔',
            '512': '新西兰',
            '513': '法属波利尼西亚',
            '514': '马里',
            '515': '瓦努阿图',
            '516': '北马里亚纳群岛',
            '517': '土耳其',
            '518': '波斯尼亚黑塞哥维那',
            '519': '利比亚',
            '520': '萨尔瓦多',
            '521': '突尼斯',
            '522': '圣克里斯托佛岛及尼维斯岛',
            '523': '阿根廷',
            '524': '也门',
            '525': '塔吉克斯坦',
            '526': '加蓬',
            '527': '斐济',
            '528': '几内亚',
            '529': '加纳',
            '531': '孟加拉国',
            '532': '图瓦卢',
            '533': '雅浦（密克罗尼西亚联邦）',
            '534': '列支敦士登',
            '535': '塞班岛',
            '536': '黎巴嫩',
            '537': '马提尼克岛',
            '538': '南非',
            '539': '贝宁',
            '540': '阿曼',
            '541': '汤加',
            '542': '斯洛伐克',
            '543': '巴巴多斯',
            '544': '摩洛哥',
            '545': '以色列',
            '546': '斯里兰卡',
            '547': '博内尔',
            '548': '波多黎各',
            '549': '蒙特塞拉特',
            '550': '土库曼斯坦',
            '551': '基里巴斯',
            '552': '几内亚比绍',
            '553': '加那利群岛',
            '554': '法属圭亚那',
            '555': '莱索托',
            '556': '泽西岛',
            '557': '多米尼加',
            '558': '埃塞俄比亚',
            '559': '伯利兹',
            '560': '根西岛',
            '561': '牙买加',
            '562': '北爱尔兰',
            '563': '智利',
            '564': '苏丹',
            '565': '科特迪瓦(象牙海岸)',
            '566': '荷属安的列斯群岛',
            '567': '科科斯群岛',
            '568': '古巴',
            '569': '摩纳哥',
            '570': '圣文森特岛',
            '571': '中国香港',
            '572': '英属维尔京群岛',
            '573': '阿森松',
            '574': '朝鲜',
            '575': '福克兰群岛',
            '576': '伊朗',
            '577': '瑙鲁',
            '578': '纽埃岛',
            '579': '巴勒斯坦',
            '580': '皮特凯恩群岛',
            '581': '圣多美和普林西比',
            '582': '圣赫勒拿岛',
            '583': '托克劳',
            '584': '博尔岛',
            '585': '圣诞岛',
            '586': '西撒哈拉',
            '587': '圣皮埃尔和密克隆群岛',
            '588': '美属维尔京群岛'

        }
        url = 'http://www.tofba.com:8081/seaair/waybills/initWaybillState?id={}'.format(id)
        headers = {
            'Host': 'www.tofba.com:8081',
            'Connection': 'keep-alive',
            'Content-Length': '0',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'Accept': 'application/json, text/plain, */*',
            'x-tofba-session-status': 'y',
            'Authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJyZWdpc3RlcmVkTW9iaWxlUGhvbmVOdW1iZXIiOiIxODAyODU2OTY0MCIsInN1YiI6IjM4NzgiLCJjdXN0b21lckxvZ2luTmFtZSI6IlNXRFpTVyIsImlzcyI6ImF1dGhvciIsImN1c3RvbWVyQ29kZSI6Iko0MjQ1IiwiaWQiOjM4NzgsImV4cCI6MTYyMTg0MzY0NiwiaWF0IjoxNjIxODQzNjQ2LCJqdGkiOiIyY2VjOTYwMC0yODI4LTRiMmQtODRmZS0yYTE1MTk2YjQwOTEiLCJjdXN0b21lck5hbWVTaG9ydCI6Iuebm-S4uueUteWtkOWVhuWKoSJ9.D4BRKMUuV5bf6JS6dkydn1-9Z0CjbOUbqppqhMviA8E',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36',
            'Origin': 'http://tofba.com:8887',
            'Referer': 'http://tofba.com:8887/',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        }
        parm = {
            'id': id
        }
        print(id)
        res = requests.post(url, headers=headers, data=parm).json()
        # print(res)
        is_ok = True
        try:
            country = jim[str(self.jiufang_id(id))]
        except Exception as g:
            country = None
        dict_ups = {'已签收': None, '已提取': None, '已到仓': None, '已清关': None, '已到港': None, '已离港': None,
                    '已放行': None, '已出库': None}
        Tracking_number = jiufang_load
        Sign_in = '否'
        Shipment_status = '正常'
        Shipment_status_ = True
        time_ = []
        title_ = []
        for j in res['data'][::-1]:
            # print(j)
            if '已' in j['content']:
                time_.append(j['operationDateTime'])
                title_.append(j['content'])

            times = j['operationDateTime']
            title = j['content']
            # if ' ' not in str(times) and '-' in str(times):
            if len(str(times)) == 10:
                times = str(times) + ' 00:00:00'
            elif len(str(times)) == 16:
                times = str(times) + ':00'
            elif len(str(times)) == 11:
                times = str(times) + ':00:00'
            # Tracking_number = jiufang_load
            remark = 'True'
            if title == '':
                remark = '无数据'
            Primary_key = zhujians + str(times) + title
            if is_ok and title in ['已签收', '已提取', '已到仓', '已清关', '已到港', '已离港', '已放行', '已出库']:
                isok = self.times_(title, 'jiufang', times)
                self.mysql_three(isok, Primary_key, times, title, Tracking_number, warehouse_sku, zhujians, remark,
                                 mysql_name='load_jiufang')
                is_ok = False
                print('jiufang:::', isok, Primary_key, times, title, Tracking_number, warehouse_sku, zhujians, remark)
            else:
                isok_ = None
                self.mysql_three(isok_, Primary_key, times, title, Tracking_number, warehouse_sku, zhujians, remark,
                                 mysql_name='load_jiufang')
                print('jiufang:::', isok_, Primary_key, times, title, Tracking_number, warehouse_sku, zhujians, remark)

            ######获取节点时间和判断物流时间是否异常
            if title == '已签收':
                dict_Signing_time = {'已签收': j['operationDateTime']}
                Sign_in = '是'
                Shipment_status_ = False
                self.mysql_guolv_save(Tracking_number)

                dict_ups.update(dict_Signing_time)



            elif title == '已提取':
                dict_Customs_clearance_time = {'已提取': j['operationDateTime']}
                dict_ups.update(dict_Customs_clearance_time)
                datetime_ = datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(
                    j['operationDateTime'].split(' ')[0],
                    '%Y-%m-%d')
                if Shipment_status_ and int(re.sub('[^0-9]', '', str(datetime_).split(', ')[0])) > 15:
                    Shipment_status = '异常'
                    Shipment_status_ = False

            elif title == '已到仓':
                dict_estimated_sailing_time = {'已到仓': j['operationDateTime']}
                dict_ups.update(dict_estimated_sailing_time)
            elif title == '已清关':
                dict_estimated_sailing_time = {'已清关': j['operationDateTime']}
                dict_ups.update(dict_estimated_sailing_time)
            elif '已到港' in title:
                dict_estimated_sailing_time = {'已到港': j['operationDateTime']}
                dict_ups.update(dict_estimated_sailing_time)
            elif title == '已离港':
                dict_estimated_sailing_time = {'已离港': j['operationDateTime']}
                dict_ups.update(dict_estimated_sailing_time)
            elif title == '已放行':
                dict_estimated_sailing_time = {'已放行': j['operationDateTime']}
                dict_ups.update(dict_estimated_sailing_time)
            elif title == '已出库':
                dict_estimated_sailing_time = {'已出库': j['operationDateTime']}
                dict_ups.update(dict_estimated_sailing_time)
        #####判断物流时间是否异常

        if res['data'][::-1][0]['content'] != '已退货' and '待' not in res['data'][::-1][-1]['content'] :
            # print(time_[0])
            new = str(datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(
                time_[0].split(' ')[0],
                '%Y-%m-%d'))
            new_ = int(re.sub('[^0-9]', '', new.split(', ')[0]))
            if Shipment_status_ and new_ > 4:
                Shipment_status = '异常'
            Latest_logistics_track, Latest_logistics_time, remarks, gold = \
                title_[0], \
                time_[0] \
                    , '', zhujians

            self.mysql_(actual_deliver_time, fbaid, country, user_account, load,
                        Delivery_method, Tracking_number, dict_ups['已出库'],
                        dict_ups['已放行'],
                        dict_ups['已离港'],
                        dict_ups['已到港'], dict_ups['已清关'], dict_ups['已到仓'], dict_ups['已提取'],
                        dict_ups['已签收'],
                        Sign_in,
                        Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)

        else:
            Latest_logistics_track, Latest_logistics_time, remarks, gold = \
                res['data'][::-1][0]['content'], \
                res['data'][::-1][0]['operationDateTime'] \
                    , '已退货', zhujians

            self.mysql_(actual_deliver_time, fbaid, country, user_account, load,
                        Delivery_method, Tracking_number, dict_ups['已出库'],
                        dict_ups['已放行'],
                        dict_ups['已离港'],
                        dict_ups['已到港'], dict_ups['已清关'], dict_ups['已到仓'], dict_ups['已提取'],
                        dict_ups['已签收'],
                        Sign_in,
                        Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)
    def jiufang_id(self, id):
        headers = {
            'Host': 'www.tofba.com:8081',
            'Connection': 'keep-alive',
            'Content-Length': '0',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'Accept': 'application/json, text/plain, */*',
            'x-tofba-session-status': 'y',
            'Authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJyZWdpc3RlcmVkTW9iaWxlUGhvbmVOdW1iZXIiOiIxODAyODU2OTY0MCIsInN1YiI6IjM4NzgiLCJjdXN0b21lckxvZ2luTmFtZSI6IlNXRFpTVyIsImlzcyI6ImF1dGhvciIsImN1c3RvbWVyQ29kZSI6Iko0MjQ1IiwiaWQiOjM4NzgsImV4cCI6MTYyMTg0MzY0NiwiaWF0IjoxNjIxODQzNjQ2LCJqdGkiOiIyY2VjOTYwMC0yODI4LTRiMmQtODRmZS0yYTE1MTk2YjQwOTEiLCJjdXN0b21lck5hbWVTaG9ydCI6Iuebm-S4uueUteWtkOWVhuWKoSJ9.D4BRKMUuV5bf6JS6dkydn1-9Z0CjbOUbqppqhMviA8E',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
            'Origin': 'http://tofba.com:8887',
            'Referer': 'http://tofba.com:8887/',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        }
        url = 'http://www.tofba.com:8081/seaair/waybills/getWaybillById?id={}'.format(id)
        res = requests.post(url, headers=headers, timeout=10).json()
        return res['data']['waybill']['countryId']

    def dhl(self, actual_deliver_time, fbaid, user_account, load, Delivery_method, dhl_load, warehouse_sku, zhujians):
        params = {
            'trackingNumber': '{}'.format(dhl_load),
            'service': 'express'
        }

        headers = {
            'Accept': 'application/json',
            'DHL-API-Key': 'UZdgzAWrQdTLNALnvAsjaCx2mXokCSC4'

        }

        url = 'https://api-eu.dhl.com/track/shipments?tracking&language=zh'
        res = requests.get(url, params=params, headers=headers)
        if res.status_code != 404 and res.status_code != 429:
        # res = requests.get(url, params=params, headers=headers).json()
            is_ok = True
            res = res.json()

            country = res['shipments'][0]['destination']['address']['addressLocality']

            dict_ups = {'已派送': None, '快件已完成清關手續並從海關放行': None, '貨件已離開DHL設施 HONG KONG - HONG KONG SAR, CHINA': None}
            Tracking_number = dhl_load
            Sign_in = '否'
            Shipment_status = '正常'
            Shipment_status_ = True

            for i in res['shipments'][0]['events']:  #
                times = i['timestamp']
                title = i['description']
                describes = i['location']['address']['addressLocality']
                # Tracking_number = dhl_load
                remark = 'True'
                if title == '':
                    remark = '无数据'
                Primary_key = zhujians + str(times) + title
                try:
                    pIds = ''
                    for o in i['pieceIds']:
                        pIds = pIds + ',' + o
                    if is_ok and title in ['已派送', '快件已完成清關手續並從海關放行', '貨件已離開DHL設施 HONG KONG - HONG KONG SAR, CHINA',
                                           '貨件已離開DHL設施 GUANGZHOU - CHINA MAINLAND']:

                        isok = self.times_(title, 'dhl', times)
                        self.mysql_two(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, pIds,
                                       zhujians, remark, mysql_name='load_dhl')
                        is_ok = False
                        print('dhl:::', isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku,
                              zhujians, remark, pIds)
                    else:
                        isok_ = None
                        self.mysql_two(isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku, pIds,
                                       zhujians, remark, mysql_name='load_dhl')
                        print('dhl:::', isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku,
                              zhujians, remark, pIds)
                except KeyError as g:
                    pIds = ''
                    if is_ok and title in ['已派送', '快件已完成清關手續並從海關放行', '貨件已離開DHL設施 HONG KONG - HONG KONG SAR, CHINA',
                                           '貨件已離開DHL設施 GUANGZHOU - CHINA MAINLAND']:

                        isok = self.times_(title, 'dhl', times)
                        self.mysql_two(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, pIds,
                                       zhujians,
                                       remark,
                                       mysql_name='load_dhl')
                        is_ok = False
                        print('dhl:::', isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku,
                              zhujians, remark, pIds)
                    else:
                        isok_ = None
                        self.mysql_two(isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku, pIds,
                                       zhujians,
                                       remark,
                                       mysql_name='load_dhl')
                        print('dhl:::', isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku,
                              zhujians, remark, pIds)

                ######获取节点时间和判断物流时间是否异常
                if '已派送' in title:
                    dict_Signing_time = {'已派送': times.split('T')[0]}
                    Sign_in = '是'
                    Shipment_status_ = False
                    self.mysql_guolv_save(Tracking_number)

                    dict_ups.update(dict_Signing_time)
                elif '海关已放行' in title:
                    dict_Customs_clearance_time = {'快件已完成清關手續並從海關放行': times.split('T')[0]}
                    dict_ups.update(dict_Customs_clearance_time)

                    datetime_ = datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(
                        i['date'],
                        '%Y-%m-%d')
                    if Shipment_status_ and int(re.sub('[^0-9]', '', str(datetime_).split(', ')[0])) > 5:
                        Shipment_status = '异常'
                        Shipment_status_ = False
                elif title == '貨件已離開DHL設施 HONG KONG - HONG KONG SAR, CHINA':
                    dict_estimated_sailing_time = {'貨件已離開DHL設施 HONG KONG - HONG KONG SAR, CHINA': times.split('T')[0]}
                    dict_ups.update(dict_estimated_sailing_time)

            #####判断物流时间是否异常
            new = str(datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(
                res['shipments'][0]['events'][0]['timestamp'].split('T')[0], '%Y-%m-%d'))
            new_ = int(re.sub('[^0-9]', '', new.split(', ')[0]))
            if Shipment_status_ and new_ > 2:
                Shipment_status = '异常'
            Release_time = None
            Departure_time = None
            Arrival_time_ = None
            Arrival_time = None
            Extraction_time = None
            Latest_logistics_track, Latest_logistics_time, remarks, gold = \
                res['shipments'][0]['status']['description'], \
                res['shipments'][0]['status']['timestamp'] \
                    , '', zhujians
            self.mysql_(actual_deliver_time, fbaid, country, user_account, load,
                        Delivery_method, Tracking_number, dict_ups['貨件已離開DHL設施 HONG KONG - HONG KONG SAR, CHINA'],
                        Release_time,
                        Departure_time,
                        Arrival_time_, dict_ups['快件已完成清關手續並從海關放行'], Arrival_time, Extraction_time, dict_ups['已派送'],
                        Sign_in,
                        Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)

    def fedex(self, actual_deliver_time, fbaid, user_account, load, Delivery_method, fedex_load, warehouse_sku,
              zhujians):
        url = 'https://www.fedex.com/trackingCal/track'
        headers = {
            'Host': 'www.fedex.com',
            # 'Content-Length': '459',
            'ADRUM': 'isAjax:true',
            'sec-ch-ua-mobile': '?0',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'https://www.fedex.com',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://www.fedex.com/zh-cn/home.html',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            # 'Cookie': 'fdx_cbid=305401236416412883752251160372821; fdx_redirect=zh-cn; isTablet=false; isMobile=false; isWireless=false; Rbt=f0; gdl-clientId=a5192140-b372-4268-a809-adbf1929f4f0; g_sref=(direct); at_check=true; _svtri=ecfb50e7-a67e-409d-8ec8-9fe70a7d53cb; AMCVS_1E22171B520E93BF0A490D44%40AdobeOrg=1; s_ecid=MCMID%7C54992833931412773701780827342782704044; s_cc=true; Nina-nina-fedex-session=%7B%22locale%22%3A%22zh_cn%22%2C%22lcstat%22%3Afalse%7D; SMIDENTITY=idV+qWJkCsdvnztPTVNdiKUjII1sBnA/UUQkhnGeCnPKBIj5QgNUBqkG8r2pgU9zjRlADcyw1UmLM7TUO66UIN5PRJnhpTBqUdEdIcvY7dfivHl5+oALxIO+RMgn3lo4ofj2KHZfcDGb0IQxeWco5VcObWOciOo8NPklIktSbNGQki+z0lySazsYvzAHXXWf1zyn/dfqwD4NDd0ayE7okv45CcjqLW0NSn3kwW8QGsGTssDIQhtiiZUCG1tHVhGCUs2SH/Hfc0aFm9eKkp5MJK8oTl+uw0Atu/kFPaL78dPveJM/MK4C2KJHQ1VYjEwapQkkM8/dKwPfCtS8jKFMib/GCO07OhJhbBhJGVbFhKhRaLF0q+4oYNEUQU+l4B5lIKuqBQ3DdLsILPdAM7ymJFTM1ClOh55q3JcgeJ+kcSgEjDM4+nib+V2pIYVScwH7mtZXowJdDgmrgPZBz6HBzjujl3sEk6cYM98xOiCAm/3sNVt4Q2q7tc0eIQaSiv0lj0dgPzr+tjtl6wejVZVVzsnknsafgBSS; g_stime=1641347636386; mbox=PC#0066215abac045968004549b45edf750.32_0#1704598260|session#a056fd3380174340b3b76e072d059358#1641355319; fdx_locale=zh_CN; setLink=%5B%5BB%5D%5D; PIM-SESSION-ID=NnrlMpgV8A6pP9Fq; siteDC=edc; AMCV_1E22171B520E93BF0A490D44%40AdobeOrg=359503849%7CMCIDTS%7C18997%7CMCMID%7C54992833931412773701780827342782704044%7CMCAAMLH-1641961234%7C11%7CMCAAMB-1641961234%7CRKhpRz8krg2tLO6pguXWp5olkAcUniQYPHaMWWgdJ3xzPWQmdj0y%7CMCOPTOUT-1641363634s%7CNONE%7CMCAID%7CNONE%7CvVersion%7C5.0.1; QSI_HistorySession=https%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641288402174%7Chttps%3A%2F%2Fwww.fedex.com%2Fzh-cn%2Fhome.html~1641347639453%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641349620457%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641349620492%7Chttps%3A%2F%2Fwww.fedex.com%2Fzh-cn%2Fhome.html~1641353460113%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353489994%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353490317%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353750035%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353750248%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355493146%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355493159%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355513873%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355513878%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355627481%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355627492%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641356435278%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641356435505; _abck=886CA23387E220405ABD0C026386EB2B~0~YAAQNtMuF/HyTA1+AQAAX07aKAcDnf87pUAcRv5zmjU2kQ0oXhZsjPj8XBEtQ2HRMj6Y3ArYRE6XguRUDTzuv998/pLGvbGj8/G2NGWbqdS1VyYSuojewjYahsZA4LBSDSeGd/g3nXNJVGN+jITDPXbwqSxgzZujI/hSsVryIvDzZiDLGyu9TsUt5+oeYdd1iFq48AO9kkNTSX74JtTqNYzTj1R8cYIHAJU852Hbu8uuwA/AFFPjJ5TNzgf5vCREOTlHSIT3jn/f9xqtfOsDjRLFlRxEIgXHHSGoKlmAefutQeUVFrVWbv8FFRSsOIpMNn4n8d7AbVDw/yfrvK06pWhGqOiVh4HaujMFULk9N0CdmNLZGydziWaw5qAkODTvZwEddqcKgPb24mB3GusyA/bEgq8NFSI=~-1~-1~-1; ak_bmsc=3B1B1730CEE2B3BD4A625885CA97688E~000000000000000000000000000000~YAAQNtMuF/LyTA1+AQAAX07aKA7ILM72JrXwkPz4UlwskAECbPUZrzeiBc73Y0XnTczADlyV8I7ZBNjOwOh3pycee5Eqv9CJA+/t8KTcV7Qn4K7sIG981Ue7FlNgxwqeHHBQqQ0DrXaRQD17/P178PbqSoiI1rkEZINZAPrjQq2+0pLT2P4TjdwHOGWv2Y62vrBQu9PdZgt5e2c963c56WwK/Cu/s81yaRcwJRJNVmBICBNv6O0MVRhx5EJakyJXIlmSVnGyiGewc8AFSry6T4on5ctGpjJ6NXXB5nDCFSf3uu48Y6QNeK9JTjyWFf5kVZxCKHjVX4sRKB4WAbKP7fGr0GV8ccS2wn3B70xNfTQcN5oSOY9ehdnkGH8=; bm_sz=517985989C7DCBD9291A9826FAF6116D~YAAQNtMuF/PyTA1+AQAAX07aKA6SuAtRC2A/7/bY+fClRzv5STq31ykGHSXbXGXd1fzIx8ljWb1wQsGD/SBsppBR//Zu0qOk0ipd5atx+JQ7uuheWCSezVzwKvIKBZQ1izhMHX+qdy/NdJmao/po9c3euMVOQYZAV7Lpyp2TVllMIeWstzKyKYlJ1YGmp30E0LNcQL7VAVePSGcN8YhBDukINN2gKLgqzHgmojygkofehh6+XsYt33TyG34EUv5YxbQgkSyHg1/lFTAzDw2hHMvS3TU8CXLOC7iqHKtaW7GALQ==~4339250~4535620; s_sess=%20setLink%3D%3B%20s_ppv%3Dfedex%252Fhero%25257Ctrack%252C88%252C47%252C2536%3B%20SC_LINKS%3Dfedex%252Ftrk-detailpage-managedelivery%255E%255E%25E7%25AE%25A1%25E7%2590%2586%25E9%2580%2592%25E9%2580%2581%255E%255Efedex%252Ftrk-detailpage-managedelivery%2520%257C%2520%25E7%25AE%25A1%25E7%2590%2586%25E9%2580%2592%25E9%2580%2581%255E%255E%3B; s_pers=%20s_vnum%3D1641398399999%2526vn%253D4%7C1641398399999%3B%20gpv_pageName%3Dfedex%252Ftrk-detailpage-managedelivery%7C1641364733138%3B%20s_invisit%3Dtrue%7C1641364733147%3B; s_sq=fedexglbl%3D%2526c.%2526a.%2526activitymap.%2526page%253Dfedex%25252Ftrk-detailpage-managedelivery%2526link%253D%2525E7%2525AE%2525A1%2525E7%252590%252586%2525E9%252580%252592%2525E9%252580%252581%2526region%253Dcontainer%2526pageIDType%253D1%2526.activitymap%2526.a%2526.c%2526pid%253Dfedex%25252Ftrk-detailpage-managedelivery%2526pidt%253D1%2526oid%253D%2525E7%2525AE%2525A1%2525E7%252590%252586%2525E9%252580%252592%2525E9%252580%252581%2526oidt%253D3%2526ot%253DSUBMIT; ADRUM=s=1641362944203&r=https%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3F476261820; xacc=CN; aemserver=PROD-P-dotcom-c0016056.prod.cloud.fedex.com; bm_mi=B8EFA7EDF504E14BEE716B87C33A72DB~6UYWZe8ZUe26CWEs8kvvIA7nSLBKORtdDvJCO4E3lMBNZdFCPDyVZ7HGBHJwqEEOrA+cMACq381mNxpNIyljJF+9c9yJiKYrkyHY7ENUjXPP1W6KFnyInYSCHS1bK002EXXUSVn3Vehau4qasIMjCfd5+qb+v7wJT1usYckYSWAnPTX09KdQAkVcZ88kiY91TdXtpe+8uMKEsLX+jRNvWsFdXgUjDlSLLVhw54T0x4ESgvunRyWpkxN2vyF6lmPpR6MYO5rw5fYlJV8qU8jkVmEd78RfzHEudi+FOxOvFUeJJbzizTU94g2TU2UZ5xnb; bm_sv=4D3E7302F82B4D249F1ADB99FB5C8029~OCgNA7VPxKgyF4fZtN9KLCu9cVEab2s+XJkyzoHuBV2QJB0LcXwRZchnjut5jaII4Ork5iPqpfawAp4vBKsLtQcofhgy0Nbh+VRekLhxpf+X8/r8KtNdM01iE7720huo0nftWA74rbz0ccdLsA4GdmsOpm5+S1dBsA3/mM1DMJk='.format(j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j)
        }
        parm1 = {
            'action': 'trackpackages',
            'data': json.dumps({"TrackPackagesRequest": {"appDeviceType": "DESKTOP", "appType": "WTRK",
                                                         "processingParameters": {}, "uniqueKey": "",
                                                         "supportCurrentLocation": True, "supportHTML": True,
                                                         "trackingInfoList": [{"trackNumberInfo": {
                                                             "trackingNumber": "{}".format(fedex_load),
                                                             "trackingQualifier": "",
                                                             "trackingCarrier": ""}}]}}),
            'format': 'json',
            'locale': 'zh_CN',
            'version': '1',

        }
        list_fedex = []

        res1 = requests.post(url, headers=headers, data=parm1, verify=False, timeout=10).json()
        country = res1['TrackPackagesResponse']['packageList'][0]['recipientCity'] + \
                  res1['TrackPackagesResponse']['packageList'][0]['recipientStateCD'] + \
                  res1['TrackPackagesResponse']['packageList'][0]['recipientCntryCD']
        number = res1['TrackPackagesResponse']['packageList'][0]['masterQualifier']  # 2459543000
        remark = 'True'

        dict_ups = {'已送达': None, '国际货物放行 - 进口': None, '已离开 FedEx 始发地服务站': None}
        Tracking_number = fedex_load
        Sign_in = '否'
        Shipment_status = '正常'
        Shipment_status_ = True

        list_fedex.append(fedex_load)
        is_ok = True
        for i in res1['TrackPackagesResponse']['packageList'][0]['scanEventList']:
            times = i['date'] + ' ' + i['time']
            title = i['status']
            describes = i['scanLocation']
            # Tracking_number = fedex_load
            zhujian = zhujians

            if title == '':
                remark = '无数据'
            Primary_key = zhujians + str(times) + title

            ######获取节点时间和判断物流时间是否异常
            if title == '已送达':
                dict_Signing_time = {'已送达': i['date']}
                Sign_in = '是'
                Shipment_status_ = False
                self.mysql_guolv_save(Tracking_number)

                dict_ups.update(dict_Signing_time)
            elif title == '国际货物放行 - 进口':
                dict_Customs_clearance_time = {'国际货物放行 - 进口': i['date']}
                dict_ups.update(dict_Customs_clearance_time)

                datetime_ = datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(i['date'],
                                                                                                         '%Y-%m-%d')
                if Shipment_status_ and int(re.sub('[^0-9]', '', str(datetime_).split(', ')[0])) > 5:
                    Shipment_status = '异常'
                    Shipment_status_ = False
            elif title == '已离开 FedEx 始发地服务站':
                dict_estimated_sailing_time = {'已离开 FedEx 始发地服务站': i['date']}
                dict_ups.update(dict_estimated_sailing_time)

            if is_ok and title in ['已送达', '国际货物放行 - 进口', '已离开 FedEx 始发地服务站']:
                isok = self.times_(title, 'fedex', times)
                self.mysql_one(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujian,
                               remark,
                               mysql_name='load_fedex')
                is_ok = False
                print('fedex:::', isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujian,
                      remark)
            else:
                isok_ = None
                self.mysql_one(isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujian,
                               remark,
                               mysql_name='load_fedex')
                print('fedex:::', isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujian,
                      remark)
        self.fedex_run1(actual_deliver_time, fbaid, user_account, load, Delivery_method, fedex_load, number,
                        warehouse_sku, zhujians, remark, list_fedex)
        #####判断物流时间是否异常
        new = str(datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(
            res1['TrackPackagesResponse']['packageList'][0]['scanEventList'][0]['date'], '%Y-%m-%d'))
        new_ = int(re.sub('[^0-9]', '', new.split(', ')[0]))
        if Shipment_status_ and new_ > 2:
            Shipment_status = '异常'
        Release_time = None
        Departure_time = None
        Arrival_time_ = None
        Arrival_time = None
        Extraction_time = None
        Latest_logistics_track, Latest_logistics_time, remarks, gold = \
            res1['TrackPackagesResponse']['packageList'][0]['scanEventList'][0]['status'], \
            res1['TrackPackagesResponse']['packageList'][0]['scanEventList'][0]['date'] \
                , '', zhujians
        self.mysql_(actual_deliver_time, fbaid, country, user_account, load,
                    Delivery_method, Tracking_number, dict_ups['已离开 FedEx 始发地服务站'], Release_time, Departure_time,
                    Arrival_time_, dict_ups['国际货物放行 - 进口'], Arrival_time, Extraction_time, dict_ups['已送达'], Sign_in,
                    Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)

    def fedex_run1(self, actual_deliver_time, fbaid, user_account, load, Delivery_method, fedex_load, number,
                   warehouse_sku, zhujians, remark, list_fedex):
        url = 'https://www.fedex.com/trackingCal/track'
        headers = {
            'Host': 'www.fedex.com',
            'Connection': 'keep-alive',
            # 'Content-Length': '459',
            'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
            'Accept': '*/*',
            'ADRUM': 'isAjax:true',
            'sec-ch-ua-mobile': '?0',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'https://www.fedex.com',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://www.fedex.com/zh-cn/home.html',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            # 'Cookie': 'fdx_cbid=305401236416412883752251160372821; fdx_redirect=zh-cn; isTablet=false; isMobile=false; isWireless=false; Rbt=f0; gdl-clientId=a5192140-b372-4268-a809-adbf1929f4f0; g_sref=(direct); at_check=true; _svtri=ecfb50e7-a67e-409d-8ec8-9fe70a7d53cb; AMCVS_1E22171B520E93BF0A490D44%40AdobeOrg=1; s_ecid=MCMID%7C54992833931412773701780827342782704044; s_cc=true; Nina-nina-fedex-session=%7B%22locale%22%3A%22zh_cn%22%2C%22lcstat%22%3Afalse%7D; SMIDENTITY=idV+qWJkCsdvnztPTVNdiKUjII1sBnA/UUQkhnGeCnPKBIj5QgNUBqkG8r2pgU9zjRlADcyw1UmLM7TUO66UIN5PRJnhpTBqUdEdIcvY7dfivHl5+oALxIO+RMgn3lo4ofj2KHZfcDGb0IQxeWco5VcObWOciOo8NPklIktSbNGQki+z0lySazsYvzAHXXWf1zyn/dfqwD4NDd0ayE7okv45CcjqLW0NSn3kwW8QGsGTssDIQhtiiZUCG1tHVhGCUs2SH/Hfc0aFm9eKkp5MJK8oTl+uw0Atu/kFPaL78dPveJM/MK4C2KJHQ1VYjEwapQkkM8/dKwPfCtS8jKFMib/GCO07OhJhbBhJGVbFhKhRaLF0q+4oYNEUQU+l4B5lIKuqBQ3DdLsILPdAM7ymJFTM1ClOh55q3JcgeJ+kcSgEjDM4+nib+V2pIYVScwH7mtZXowJdDgmrgPZBz6HBzjujl3sEk6cYM98xOiCAm/3sNVt4Q2q7tc0eIQaSiv0lj0dgPzr+tjtl6wejVZVVzsnknsafgBSS; g_stime=1641347636386; mbox=PC#0066215abac045968004549b45edf750.32_0#1704598260|session#a056fd3380174340b3b76e072d059358#1641355319; fdx_locale=zh_CN; setLink=%5B%5BB%5D%5D; PIM-SESSION-ID=NnrlMpgV8A6pP9Fq; siteDC=edc; AMCV_1E22171B520E93BF0A490D44%40AdobeOrg=359503849%7CMCIDTS%7C18997%7CMCMID%7C54992833931412773701780827342782704044%7CMCAAMLH-1641961234%7C11%7CMCAAMB-1641961234%7CRKhpRz8krg2tLO6pguXWp5olkAcUniQYPHaMWWgdJ3xzPWQmdj0y%7CMCOPTOUT-1641363634s%7CNONE%7CMCAID%7CNONE%7CvVersion%7C5.0.1; QSI_HistorySession=https%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641288402174%7Chttps%3A%2F%2Fwww.fedex.com%2Fzh-cn%2Fhome.html~1641347639453%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641349620457%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641349620492%7Chttps%3A%2F%2Fwww.fedex.com%2Fzh-cn%2Fhome.html~1641353460113%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353489994%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353490317%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353750035%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353750248%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355493146%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355493159%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355513873%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355513878%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355627481%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355627492%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641356435278%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641356435505; _abck=886CA23387E220405ABD0C026386EB2B~0~YAAQNtMuF/HyTA1+AQAAX07aKAcDnf87pUAcRv5zmjU2kQ0oXhZsjPj8XBEtQ2HRMj6Y3ArYRE6XguRUDTzuv998/pLGvbGj8/G2NGWbqdS1VyYSuojewjYahsZA4LBSDSeGd/g3nXNJVGN+jITDPXbwqSxgzZujI/hSsVryIvDzZiDLGyu9TsUt5+oeYdd1iFq48AO9kkNTSX74JtTqNYzTj1R8cYIHAJU852Hbu8uuwA/AFFPjJ5TNzgf5vCREOTlHSIT3jn/f9xqtfOsDjRLFlRxEIgXHHSGoKlmAefutQeUVFrVWbv8FFRSsOIpMNn4n8d7AbVDw/yfrvK06pWhGqOiVh4HaujMFULk9N0CdmNLZGydziWaw5qAkODTvZwEddqcKgPb24mB3GusyA/bEgq8NFSI=~-1~-1~-1; ak_bmsc=3B1B1730CEE2B3BD4A625885CA97688E~000000000000000000000000000000~YAAQNtMuF/LyTA1+AQAAX07aKA7ILM72JrXwkPz4UlwskAECbPUZrzeiBc73Y0XnTczADlyV8I7ZBNjOwOh3pycee5Eqv9CJA+/t8KTcV7Qn4K7sIG981Ue7FlNgxwqeHHBQqQ0DrXaRQD17/P178PbqSoiI1rkEZINZAPrjQq2+0pLT2P4TjdwHOGWv2Y62vrBQu9PdZgt5e2c963c56WwK/Cu/s81yaRcwJRJNVmBICBNv6O0MVRhx5EJakyJXIlmSVnGyiGewc8AFSry6T4on5ctGpjJ6NXXB5nDCFSf3uu48Y6QNeK9JTjyWFf5kVZxCKHjVX4sRKB4WAbKP7fGr0GV8ccS2wn3B70xNfTQcN5oSOY9ehdnkGH8=; bm_sz=517985989C7DCBD9291A9826FAF6116D~YAAQNtMuF/PyTA1+AQAAX07aKA6SuAtRC2A/7/bY+fClRzv5STq31ykGHSXbXGXd1fzIx8ljWb1wQsGD/SBsppBR//Zu0qOk0ipd5atx+JQ7uuheWCSezVzwKvIKBZQ1izhMHX+qdy/NdJmao/po9c3euMVOQYZAV7Lpyp2TVllMIeWstzKyKYlJ1YGmp30E0LNcQL7VAVePSGcN8YhBDukINN2gKLgqzHgmojygkofehh6+XsYt33TyG34EUv5YxbQgkSyHg1/lFTAzDw2hHMvS3TU8CXLOC7iqHKtaW7GALQ==~4339250~4535620; s_sess=%20setLink%3D%3B%20s_ppv%3Dfedex%252Fhero%25257Ctrack%252C88%252C47%252C2536%3B%20SC_LINKS%3Dfedex%252Ftrk-detailpage-managedelivery%255E%255E%25E7%25AE%25A1%25E7%2590%2586%25E9%2580%2592%25E9%2580%2581%255E%255Efedex%252Ftrk-detailpage-managedelivery%2520%257C%2520%25E7%25AE%25A1%25E7%2590%2586%25E9%2580%2592%25E9%2580%2581%255E%255E%3B; s_pers=%20s_vnum%3D1641398399999%2526vn%253D4%7C1641398399999%3B%20gpv_pageName%3Dfedex%252Ftrk-detailpage-managedelivery%7C1641364733138%3B%20s_invisit%3Dtrue%7C1641364733147%3B; s_sq=fedexglbl%3D%2526c.%2526a.%2526activitymap.%2526page%253Dfedex%25252Ftrk-detailpage-managedelivery%2526link%253D%2525E7%2525AE%2525A1%2525E7%252590%252586%2525E9%252580%252592%2525E9%252580%252581%2526region%253Dcontainer%2526pageIDType%253D1%2526.activitymap%2526.a%2526.c%2526pid%253Dfedex%25252Ftrk-detailpage-managedelivery%2526pidt%253D1%2526oid%253D%2525E7%2525AE%2525A1%2525E7%252590%252586%2525E9%252580%252592%2525E9%252580%252581%2526oidt%253D3%2526ot%253DSUBMIT; ADRUM=s=1641362944203&r=https%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3F476261820; xacc=CN; aemserver=PROD-P-dotcom-c0016056.prod.cloud.fedex.com; bm_mi=B8EFA7EDF504E14BEE716B87C33A72DB~6UYWZe8ZUe26CWEs8kvvIA7nSLBKORtdDvJCO4E3lMBNZdFCPDyVZ7HGBHJwqEEOrA+cMACq381mNxpNIyljJF+9c9yJiKYrkyHY7ENUjXPP1W6KFnyInYSCHS1bK002EXXUSVn3Vehau4qasIMjCfd5+qb+v7wJT1usYckYSWAnPTX09KdQAkVcZ88kiY91TdXtpe+8uMKEsLX+jRNvWsFdXgUjDlSLLVhw54T0x4ESgvunRyWpkxN2vyF6lmPpR6MYO5rw5fYlJV8qU8jkVmEd78RfzHEudi+FOxOvFUeJJbzizTU94g2TU2UZ5xnb; bm_sv=4D3E7302F82B4D249F1ADB99FB5C8029~OCgNA7VPxKgyF4fZtN9KLCu9cVEab2s+XJkyzoHuBV2QJB0LcXwRZchnjut5jaII4Ork5iPqpfawAp4vBKsLtQcofhgy0Nbh+VRekLhxpf+X8/r8KtNdM01iE7720huo0nftWA74rbz0ccdLsA4GdmsOpm5+S1dBsA3/mM1DMJk='.format(j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j)
        }
        parm1 = {
            'action': 'getAssociatedShipments',
            'data': json.dumps({"AssociatedShipmentRequest": {"appDeviceType": "DESKTOP", "appType": "WTRK",
                                                              "processingParameters": {}, "uniqueKey": "",
                                                              "masterTrackingNumberInfo": {"associatedType": "MPS",
                                                                                           "trackingNumberInfo": {
                                                                                               "trackingCarrier": "",
                                                                                               "trackingNumber": "{}".format(
                                                                                                   fedex_load),
                                                                                               "trackingQualifier": "{}".format(
                                                                                                   number)}}}}),
            'format': 'json',
            'locale': 'zh_CN',
            'version': '1',

        }

        res1 = requests.post(url, headers=headers, data=parm1, verify=False, timeout=10).json()
        for i in res1['AssociatedShipmentsResponse']['associatedShipmentList']:  # [1:]
            track = i['trackingNbr']
            if track not in list_fedex:
                self.fedex_run2(actual_deliver_time, fbaid, user_account, load, Delivery_method, track, warehouse_sku,
                                zhujians, remark)

    def fedex_run2(self, actual_deliver_time, fbaid, user_account, load, Delivery_method, track, warehouse_sku,
                   zhujians, remark):
        url = 'https://www.fedex.com/trackingCal/track'
        headers = {
            'Host': 'www.fedex.com',
            'Connection': 'keep-alive',
            # 'Content-Length': '459',
            'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
            'Accept': '*/*',
            'ADRUM': 'isAjax:true',
            'sec-ch-ua-mobile': '?0',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'https://www.fedex.com',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://www.fedex.com/zh-cn/home.html',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            # 'Cookie': 'fdx_cbid=305401236416412883752251160372821; fdx_redirect=zh-cn; isTablet=false; isMobile=false; isWireless=false; Rbt=f0; gdl-clientId=a5192140-b372-4268-a809-adbf1929f4f0; g_sref=(direct); at_check=true; _svtri=ecfb50e7-a67e-409d-8ec8-9fe70a7d53cb; AMCVS_1E22171B520E93BF0A490D44%40AdobeOrg=1; s_ecid=MCMID%7C54992833931412773701780827342782704044; s_cc=true; Nina-nina-fedex-session=%7B%22locale%22%3A%22zh_cn%22%2C%22lcstat%22%3Afalse%7D; SMIDENTITY=idV+qWJkCsdvnztPTVNdiKUjII1sBnA/UUQkhnGeCnPKBIj5QgNUBqkG8r2pgU9zjRlADcyw1UmLM7TUO66UIN5PRJnhpTBqUdEdIcvY7dfivHl5+oALxIO+RMgn3lo4ofj2KHZfcDGb0IQxeWco5VcObWOciOo8NPklIktSbNGQki+z0lySazsYvzAHXXWf1zyn/dfqwD4NDd0ayE7okv45CcjqLW0NSn3kwW8QGsGTssDIQhtiiZUCG1tHVhGCUs2SH/Hfc0aFm9eKkp5MJK8oTl+uw0Atu/kFPaL78dPveJM/MK4C2KJHQ1VYjEwapQkkM8/dKwPfCtS8jKFMib/GCO07OhJhbBhJGVbFhKhRaLF0q+4oYNEUQU+l4B5lIKuqBQ3DdLsILPdAM7ymJFTM1ClOh55q3JcgeJ+kcSgEjDM4+nib+V2pIYVScwH7mtZXowJdDgmrgPZBz6HBzjujl3sEk6cYM98xOiCAm/3sNVt4Q2q7tc0eIQaSiv0lj0dgPzr+tjtl6wejVZVVzsnknsafgBSS; g_stime=1641347636386; mbox=PC#0066215abac045968004549b45edf750.32_0#1704598260|session#a056fd3380174340b3b76e072d059358#1641355319; fdx_locale=zh_CN; setLink=%5B%5BB%5D%5D; PIM-SESSION-ID=NnrlMpgV8A6pP9Fq; siteDC=edc; AMCV_1E22171B520E93BF0A490D44%40AdobeOrg=359503849%7CMCIDTS%7C18997%7CMCMID%7C54992833931412773701780827342782704044%7CMCAAMLH-1641961234%7C11%7CMCAAMB-1641961234%7CRKhpRz8krg2tLO6pguXWp5olkAcUniQYPHaMWWgdJ3xzPWQmdj0y%7CMCOPTOUT-1641363634s%7CNONE%7CMCAID%7CNONE%7CvVersion%7C5.0.1; QSI_HistorySession=https%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641288402174%7Chttps%3A%2F%2Fwww.fedex.com%2Fzh-cn%2Fhome.html~1641347639453%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641349620457%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641349620492%7Chttps%3A%2F%2Fwww.fedex.com%2Fzh-cn%2Fhome.html~1641353460113%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353489994%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353490317%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353750035%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641353750248%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355493146%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355493159%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355513873%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355513878%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355627481%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641355627492%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641356435278%7Chttps%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3Ftrknbr%3D{}%26trkqual%3D2459543000~{}~FX~1641356435505; _abck=886CA23387E220405ABD0C026386EB2B~0~YAAQNtMuF/HyTA1+AQAAX07aKAcDnf87pUAcRv5zmjU2kQ0oXhZsjPj8XBEtQ2HRMj6Y3ArYRE6XguRUDTzuv998/pLGvbGj8/G2NGWbqdS1VyYSuojewjYahsZA4LBSDSeGd/g3nXNJVGN+jITDPXbwqSxgzZujI/hSsVryIvDzZiDLGyu9TsUt5+oeYdd1iFq48AO9kkNTSX74JtTqNYzTj1R8cYIHAJU852Hbu8uuwA/AFFPjJ5TNzgf5vCREOTlHSIT3jn/f9xqtfOsDjRLFlRxEIgXHHSGoKlmAefutQeUVFrVWbv8FFRSsOIpMNn4n8d7AbVDw/yfrvK06pWhGqOiVh4HaujMFULk9N0CdmNLZGydziWaw5qAkODTvZwEddqcKgPb24mB3GusyA/bEgq8NFSI=~-1~-1~-1; ak_bmsc=3B1B1730CEE2B3BD4A625885CA97688E~000000000000000000000000000000~YAAQNtMuF/LyTA1+AQAAX07aKA7ILM72JrXwkPz4UlwskAECbPUZrzeiBc73Y0XnTczADlyV8I7ZBNjOwOh3pycee5Eqv9CJA+/t8KTcV7Qn4K7sIG981Ue7FlNgxwqeHHBQqQ0DrXaRQD17/P178PbqSoiI1rkEZINZAPrjQq2+0pLT2P4TjdwHOGWv2Y62vrBQu9PdZgt5e2c963c56WwK/Cu/s81yaRcwJRJNVmBICBNv6O0MVRhx5EJakyJXIlmSVnGyiGewc8AFSry6T4on5ctGpjJ6NXXB5nDCFSf3uu48Y6QNeK9JTjyWFf5kVZxCKHjVX4sRKB4WAbKP7fGr0GV8ccS2wn3B70xNfTQcN5oSOY9ehdnkGH8=; bm_sz=517985989C7DCBD9291A9826FAF6116D~YAAQNtMuF/PyTA1+AQAAX07aKA6SuAtRC2A/7/bY+fClRzv5STq31ykGHSXbXGXd1fzIx8ljWb1wQsGD/SBsppBR//Zu0qOk0ipd5atx+JQ7uuheWCSezVzwKvIKBZQ1izhMHX+qdy/NdJmao/po9c3euMVOQYZAV7Lpyp2TVllMIeWstzKyKYlJ1YGmp30E0LNcQL7VAVePSGcN8YhBDukINN2gKLgqzHgmojygkofehh6+XsYt33TyG34EUv5YxbQgkSyHg1/lFTAzDw2hHMvS3TU8CXLOC7iqHKtaW7GALQ==~4339250~4535620; s_sess=%20setLink%3D%3B%20s_ppv%3Dfedex%252Fhero%25257Ctrack%252C88%252C47%252C2536%3B%20SC_LINKS%3Dfedex%252Ftrk-detailpage-managedelivery%255E%255E%25E7%25AE%25A1%25E7%2590%2586%25E9%2580%2592%25E9%2580%2581%255E%255Efedex%252Ftrk-detailpage-managedelivery%2520%257C%2520%25E7%25AE%25A1%25E7%2590%2586%25E9%2580%2592%25E9%2580%2581%255E%255E%3B; s_pers=%20s_vnum%3D1641398399999%2526vn%253D4%7C1641398399999%3B%20gpv_pageName%3Dfedex%252Ftrk-detailpage-managedelivery%7C1641364733138%3B%20s_invisit%3Dtrue%7C1641364733147%3B; s_sq=fedexglbl%3D%2526c.%2526a.%2526activitymap.%2526page%253Dfedex%25252Ftrk-detailpage-managedelivery%2526link%253D%2525E7%2525AE%2525A1%2525E7%252590%252586%2525E9%252580%252592%2525E9%252580%252581%2526region%253Dcontainer%2526pageIDType%253D1%2526.activitymap%2526.a%2526.c%2526pid%253Dfedex%25252Ftrk-detailpage-managedelivery%2526pidt%253D1%2526oid%253D%2525E7%2525AE%2525A1%2525E7%252590%252586%2525E9%252580%252592%2525E9%252580%252581%2526oidt%253D3%2526ot%253DSUBMIT; ADRUM=s=1641362944203&r=https%3A%2F%2Fwww.fedex.com%2Ffedextrack%2F%3F476261820; xacc=CN; aemserver=PROD-P-dotcom-c0016056.prod.cloud.fedex.com; bm_mi=B8EFA7EDF504E14BEE716B87C33A72DB~6UYWZe8ZUe26CWEs8kvvIA7nSLBKORtdDvJCO4E3lMBNZdFCPDyVZ7HGBHJwqEEOrA+cMACq381mNxpNIyljJF+9c9yJiKYrkyHY7ENUjXPP1W6KFnyInYSCHS1bK002EXXUSVn3Vehau4qasIMjCfd5+qb+v7wJT1usYckYSWAnPTX09KdQAkVcZ88kiY91TdXtpe+8uMKEsLX+jRNvWsFdXgUjDlSLLVhw54T0x4ESgvunRyWpkxN2vyF6lmPpR6MYO5rw5fYlJV8qU8jkVmEd78RfzHEudi+FOxOvFUeJJbzizTU94g2TU2UZ5xnb; bm_sv=4D3E7302F82B4D249F1ADB99FB5C8029~OCgNA7VPxKgyF4fZtN9KLCu9cVEab2s+XJkyzoHuBV2QJB0LcXwRZchnjut5jaII4Ork5iPqpfawAp4vBKsLtQcofhgy0Nbh+VRekLhxpf+X8/r8KtNdM01iE7720huo0nftWA74rbz0ccdLsA4GdmsOpm5+S1dBsA3/mM1DMJk='.format(j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j,j)
        }
        parm1 = {
            'action': 'trackpackages',
            'data': json.dumps({"TrackPackagesRequest": {"appDeviceType": "DESKTOP", "appType": "WTRK",
                                                         "processingParameters": {}, "uniqueKey": "",
                                                         "supportCurrentLocation": True, "supportHTML": True,
                                                         "trackingInfoList": [{"trackNumberInfo": {
                                                             "trackingNumber": "{}".format(track),
                                                             "trackingQualifier": "",
                                                             "trackingCarrier": ""}}]}}),
            'format': 'json',
            'locale': 'zh_CN',
            'version': '1',

        }

        res1 = requests.post(url, headers=headers, data=parm1, verify=False, timeout=10).json()
        country = res1['TrackPackagesResponse']['packageList'][0]['recipientCity'] + \
                  res1['TrackPackagesResponse']['packageList'][0]['recipientStateCD'] + \
                  res1['TrackPackagesResponse']['packageList'][0]['recipientCntryCD']
        is_ok = True

        dict_ups = {'已送达': None, '国际货物放行 - 进口': None, '已离开 FedEx 始发地服务站': None}
        Tracking_number = track
        Sign_in = '否'
        Shipment_status = '正常'
        Shipment_status_ = True

        for i in res1['TrackPackagesResponse']['packageList'][0]['scanEventList']:
            times = i['date'] + i['time']
            title = i['status']
            describes = i['scanLocation']
            # Tracking_number = track
            Primary_key = zhujians + str(times) + title

            if is_ok and title in ['已送达', '国际货物放行 - 进口', '已离开 FedEx 始发地服务站']:
                isok = self.times_(title, 'fedex', times)
                self.mysql_one(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                               remark,
                               mysql_name='load_fedex')
                is_ok = False
                print('fedex:::', isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                      remark)
            else:
                isok_ = None
                self.mysql_one(isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                               remark,
                               mysql_name='load_fedex')
                print('fedex:::', isok_, Primary_key, times, title, describes, Tracking_number, warehouse_sku, zhujians,
                      remark)

            ######获取节点时间和判断物流时间是否异常
            if title == '已送达':
                dict_Signing_time = {'已送达': i['date']}
                Sign_in = '是'
                Shipment_status_ = False
                self.mysql_guolv_save(Tracking_number)

                dict_ups.update(dict_Signing_time)
            elif title == '国际货物放行 - 进口':
                dict_Customs_clearance_time = {'国际货物放行 - 进口': i['date']}
                dict_ups.update(dict_Customs_clearance_time)

                datetime_ = datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(i['date'],
                                                                                                         '%Y-%m-%d')
                if Shipment_status_ and int(re.sub('[^0-9]', '', str(datetime_).split(', ')[0])) > 5:
                    Shipment_status = '异常'
                    Shipment_status_ = False
            elif title == '已离开 FedEx 始发地服务站':
                dict_estimated_sailing_time = {'已离开 FedEx 始发地服务站': i['date']}
                dict_ups.update(dict_estimated_sailing_time)

        #####判断物流时间是否异常
        new = str(datetime.datetime.strptime(newtime, '%Y-%m-%d') - datetime.datetime.strptime(
            res1['TrackPackagesResponse']['packageList'][0]['scanEventList'][0]['date'], '%Y-%m-%d'))
        new_ = int(re.sub('[^0-9]', '', new.split(', ')[0]))
        if Shipment_status_ and new_ > 2:
            Shipment_status = '异常'
        Release_time = None
        Departure_time = None
        Arrival_time_ = None
        Arrival_time = None
        Extraction_time = None
        Latest_logistics_track, Latest_logistics_time, remarks, gold = \
            res1['TrackPackagesResponse']['packageList'][0]['scanEventList'][0]['status'], \
            res1['TrackPackagesResponse']['packageList'][0]['scanEventList'][0]['date'] \
                , '', zhujians
        self.mysql_(actual_deliver_time, fbaid, country, user_account, load,
                    Delivery_method, Tracking_number, dict_ups['已离开 FedEx 始发地服务站'], Release_time, Departure_time,
                    Arrival_time_, dict_ups['国际货物放行 - 进口'], Arrival_time, Extraction_time, dict_ups['已送达'], Sign_in,
                    Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)

    def ups(self, actual_deliver_time, fbaid, user_account, load, Delivery_method, ups_load, warehouse_sku, zhujians):

        url = 'https://www.ups.com/track/api/Track/GetStatus?loc=zh_HK'
        headers = {
            'cookie': f'CONSENTMGR=consent:true|ts:1647847860847; _gcl_au=1.1.1194978576.1647847862; aam_cms=segments=22945447|9626568|9626828|9625302; aam_uuid=60884968402242304342962892665125856077; ups_language_preference=en_HK; HASSEENNOTICE=TRUE; sharedsession=1282224c-59cd-4c31-b649-c207533cfb5b:m; at_check=true; AMCVS_036784BD57A8BB277F000101@AdobeOrg=1; s_cc=true; X-CSRF-TOKEN=CfDJ8Jcj9GhlwkdBikuRYzfhrpLPL9TdEw2J1lojUsQsCMmqUOsQoHpKjvcNWRN89apnyM5PHpwpe6ePjdglD9ygH4TinE0t0eOzoX_y4pXoBH1EUO90anEJwG1BhDrB8Dr1YSkghRdQyZXTRKaHNVb5wDE; PIM-SESSION-ID=OCLJmdh7EbyzfJzl; _fbp=fb.1.1648112599480.781951500; s_vnum=1648742400493&vn=6; s_invisit=true; dayssincevisit_s=Less than 1 day; bm_sz=F2266D44C03705E506EB9560BD8281AB~YAAQe0InOyw86Z9/AQAANNKavg/jStdHX536X+xtK5p0uzM1gVvzAT0XzrmLsLn7vIly0T/PdvkO6u/AbAs48CpF+X1j+bGeLlsjzI4UwQE6KYW+26+caR/OCWjwfpjoId+3y6A7biUDYpYAO4bSg15MrkPSM531aRWm0cfMWgqt+ZhdtlVXnJhaqL2eHAJ6NomHDQXjflFMhzn3gWjW8+YY6PAXSQtzk6uhXbf9Sl8gofIDqyPvVjEcvUFtguI1AtSb5Wv/BuygvzWMw+PcjNcY5ZihNme3X4sUSEqgRRQ=~4342833~3752503; mboxEdgeCluster=32; ak_bmsc=D3831C226206BEE89A1904CA6F23E3D2~000000000000000000000000000000~YAAQe0InO6E86Z9/AQAAyNiavg9ai7NT8RdVvvGVIXNa5V/cNtNesbeef2OJkqxrhxqqnYLS6osroI+UeESFue44VhcT7MNpRs7GWifK5YnMUEk1UIxqBd52F6TrRGyTLR4Pve/vnLPflHXakROhutQ+PlQtHOhQuG8Aq8Pr/ceJokN9nJQ3Ek9lKowR0fu1FjIWJ25XZzS4wLCoqjaWjsZlflQlMZYVFuATBMgnGRZN2kYFMv0f9bpLF42fkhM0eFph4MF0J547eC6V8iwTJGtrv7OM5G3kcS1cgw3taSf3VCDHSuCYKPCi0vRvyANuCDrJgCG9Ds6O3pdKAt+JEyNiEnrDQtgRPiNBmlU843dxbFNx4l+gTaGmI//t3VVIs3TuBrmdNeEg9ohCHAqoXjJKUiTp3atzouU83p1Z1ukOn0qr3yMWllkBgnSc9kDp7mUBfeYlAJKXttNn1SpT9sn+ARGfDLlYMelH5xFmPNNHSbZOT2TxAw==; AMCV_036784BD57A8BB277F000101@AdobeOrg=-1124106680|MCIDTS|19076|MCMID|61141257874973915903006537245434759817|MCAAMLH-1648775093|11|MCAAMB-1648775093|RKhpRz8krg2tLO6pguXWp5olkAcUniQYPHaMWWgdJ3xzPWQmdj0y|MCOPTOUT-1648177493s|NONE|MCCIDH|-383860148|vVersion|5.2.0; st_cur_page=st_track; s_nr=1648170844515-Repeat; dayssincevisit=1648170844516; JSESSIONID=11C42E1CC88A9138D60F369DB1981FDC; X-XSRF-TOKEN-ST=CfDJ8Jcj9GhlwkdBikuRYzfhrpISuM5wK-QCd1Oav-hIZtCYcHo36Bzk8iCmTRNkQ6MgbcTmBdY92S3Vz0eAvgJvBI-zHFiuWOJq_IeltJgsugTGPOZDtqdFCTOUWxo99LdZesdl7bVHN04sWaX3ihTAZFo; utag_main=v_id:017fab62ea61001f4f55a969463e05073003106b00bd0$_sn:5$_se:10$_ss:0$_st:1648172689863$vapi_domain:ups.com$ses_id:1648170289277;exp-session$_pn:6;exp-session$fs_sample_user:undefined;exp-session$_prevpage:ups:hk:en:track;exp-1648174444316$_prevpageid:tracking/trackWeb/tra(3det).html;exp-1648174444317; RT="z=1&dm=ups.com&si=e562885e-e392-49cd-8025-f6db0a16ae89&ss=l15q1dwa&sl=4&tt=1mn9&bcn=//684d0d4c.akstat.io/"; _abck=8CFA76189773CD95D863E67F75026CA1~0~YAAQZ8U8t2Dy6Lp/AQAAAvejvgdQFOJWtnLqiFo9JaXlbbd/qC1q+sqkPVLFWwutEIxhAAmzFsH3f0EuxNICM5cuNuYpvmTFrNra2SQbhuawMGWscZ1Qo+UY2NZW5GNwANIjdF6JBn9vJyrrees3hathzBiVqIauhqU8HVwY75K5UMs7wpjEChShMWPf//pUF5g87qAZ8sTprWZ1XlLOCg/LR+SI4FbRRp5+AuGMTlwO7h3ZC+BByibxAmtsybyM0Ulcg6l9OKXuME/7ATy8/BaSpfy07YUGy67Opxheun/joePee1NBrDUpxSac1DUPfy9DsLxPeCV7NwgFpSok76w+vKwBB5tAEAVpSizGq/M4EGv4LBaGYugT7EpFSRQWRrPd7bgsiBLcV6z0nzZIopoXMG79~-1~-1~-1; mbox=PC#96acf6b654154f17a5c44cbef5f9943c.32_0#1711415691|session#c1f09041fe4e4fc08003f17fc0ec02b4#1648172152',
            'referer': 'https://www.ups.com/track?loc=zh_HK&requester=ST/trackdetails',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
            'x-xsrf-token': 'CfDJ8Jcj9GhlwkdBikuRYzfhrpISuM5wK-QCd1Oav-hIZtCYcHo36Bzk8iCmTRNkQ6MgbcTmBdY92S3Vz0eAvgJvBI-zHFiuWOJq_IeltJgsugTGPOZDtqdFCTOUWxo99LdZesdl7bVHN04sWaX3ihTAZFo'
        }
        http_ = requests.get(
            'http://api.tianqiip.com/getip?secret=332jxwphs8r06htn&type=txt&num=1&time=3&port=1').text.strip()
        proxy = {
            'http': '117.94.112.143:36166',
            'https': '117.94.112.143:36166',
        }
        parm = {"Locale": "zh_HK", "TrackingNumber": ["{}".format(ups_load)], "Requester": "st/trackdetails",
                "returnToValue": ""}
        # print(proxies)
        data_ = False
        res = requests.post(url, headers=headers, json=parm, verify=False)
        if res.status_code == 200:
            # res = requests.post(url, headers=headers, json=parm, timeout=10).json()

            if res.json()['statusCode'] == 200 and res.json()["trackDetails"][0]["shipmentProgressActivities"] != None:
                print(res.text)
                data_ = True
                # for i in res.json()["trackDetails"][0]["shipmentProgressActivities"]:
                #     times = i['date'] + ' ' + i['time']
                #     title = i['activityScan'].strip()
                #     print(times,title)
            else:
                print('没空')

        if data_:
            try:
                country = res.json()["trackDetails"][0]["shipToAddress"]['city'] + \
                          res.json()["trackDetails"][0]["shipToAddress"]['country'] + \
                          res.json()["trackDetails"][0]["shipToAddress"]['state']
            except Exception as f:
                country = None
                print()
            dict_ups = {'已派送': None, '進口清關': None, '從設施出發': None}
            Tracking_number = ups_load
            Sign_in = '否'
            Shipment_status = '正常'
            Shipment_status_ = True
            #
            for i in res.json()["trackDetails"][0]["shipmentProgressActivities"]:
                times = i['date'] + ' ' + i['time']
                title = i['activityScan'].strip()
                describes = i['location']
                # Tracking_number = ups_load
                remark = 'True'
                datatime_time = res.json()["trackDetails"][0]['deliveredDate'] + ' ' + res.json()["trackDetails"][0][
                    'deliveredTime']
                isok = datetime.datetime.strptime(datatime_time, '%Y/%m/%d %H:%M')

                if title == '' and describes == '' and times == '':
                    remark = '无数据'
                Primary_key = zhujians + str(times) + title

                self.mysql_one(isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku,
                               zhujians, remark,
                               mysql_name='load_ups')

                ######获取节点时间和判断物流时间是否异常
                if title == '已派送':
                    dict_Signing_time = {'已派送': i['date']}
                    dict_ups.update(dict_Signing_time)
                    Sign_in = '是'
                    Shipment_status_ = False
                    self.mysql_guolv_save(Tracking_number)

                    dict_ups.update(dict_Signing_time)
                elif '清關' in title:
                    dict_Customs_clearance_time = {'進口清關': i['date']}
                    dict_ups.update(dict_Customs_clearance_time)
                    if Delivery_method == '快递':
                        datetime_ = datetime.datetime.strptime(newtime, '%Y/%m/%d') - datetime.datetime.strptime(
                            i['date'],
                            '%Y/%m/%d')
                        if Shipment_status_ and int(re.sub('[^0-9]', '', str(datetime_).split(', ')[0])) > 5:
                            Shipment_status = '异常'
                            Shipment_status_ = False



                elif title == '從設施出發':
                    dict_estimated_sailing_time = {'從設施出發': i['date']}
                    dict_ups.update(dict_estimated_sailing_time)

                print('ups:::', isok, Primary_key, times, title, describes, Tracking_number, warehouse_sku,
                      zhujians, remark)
            ######当天时间判断物流时间是否异常
            if Shipment_status_ and Delivery_method == '快递':
                new = str(datetime.datetime.strptime(newtime, '%Y/%m/%d') - datetime.datetime.strptime(
                    res.json()["trackDetails"][0]["shipmentProgressActivities"][0]['date'], '%Y/%m/%d'))
                new_ = int(re.sub('[^0-9]', '', new.split(', ')[0]))
                if Shipment_status_ and new_ > 2:
                    Shipment_status = '异常'
            elif Shipment_status_ and Delivery_method == '海快':
                newtime1 = time.strftime('%Y/%m/%d %H:%M:%S')
                newtime_ = datetime.datetime.strptime(newtime1, '%Y/%m/%d %H:%M:%S') - self.day_(actual_deliver_time)
                if int(re.sub('[^0-9]', '', str(newtime_).split(', ')[0])) > 20:
                    Shipment_status = '异常'

            Release_time = None
            Departure_time = None
            Arrival_time_ = None
            Arrival_time = None
            Extraction_time = None
            Latest_logistics_track, Latest_logistics_time, remarks, gold = \
                res.json()["trackDetails"][0]["shipmentProgressActivities"][0]['activityScan'], \
                res.json()["trackDetails"][0]["shipmentProgressActivities"][0]['date'] \
                    , '', zhujians
            self.mysql_(actual_deliver_time, fbaid, country, user_account, load,
                        Delivery_method, Tracking_number, dict_ups['從設施出發'], Release_time, Departure_time,
                        Arrival_time_, dict_ups['進口清關'], Arrival_time, Extraction_time, dict_ups['已派送'], Sign_in,
                        Latest_logistics_track, Latest_logistics_time, Shipment_status, remarks, gold)

    def times_(self, datas, datas_, datatime_time):  # datas物流title，datas_物流平台，datatime_time节点时间,计算预计送达时间

        if datas_ == 'jiufang':
            datatime_time = datetime.datetime.strptime(datatime_time, '%Y-%m-%d %H:%M:%S')
            if '已提取' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=2)
                return '{}'.format(datatime_)
            elif '已到仓' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=4)
                return '{}'.format(datatime_)
            elif '已清关' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=6)
                return '{}'.format(datatime_)
            elif '已到港' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=7)
                return '{}'.format(datatime_)
            elif '已离港' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=9)
                return '{}'.format(datatime_)
            elif '已放行' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=10)
                return '{}'.format(datatime_)
            elif '已出库' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=11)
                return '{}'.format(datatime_)
            else:
                return None
        elif datas_ == 'dhl':
            datatime_time = datatime_time.replace('T', ' ')
            datatime_time = datetime.datetime.strptime(datatime_time, '%Y-%m-%d %H:%M:%S')
            if '已派送' in datas :
                return '{}'.format(datatime_time)
            elif '快件已完成清關手續並從海關放行' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=5)
                return '{}'.format(datatime_)
            elif '貨件已離開DHL設施 HONG KONG - HONG KONG SAR, CHINA' in datas or '貨件已離開DHL設施 GUANGZHOU - CHINA MAINLAND' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=7)
                return '{}'.format(datatime_)
            else:
                return None

        elif datas_ == 'fedex':
            datatime_time = datetime.datetime.strptime(datatime_time, '%Y-%m-%d %H:%M:%S')
            if '国际货物放行 - 进口' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=5)
                return '{}'.format(datatime_)
            elif '已离开 FedEx 始发地服务站' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=7)
                return '{}'.format(datatime_)
            else:
                return None
        elif datas_ == 'aff':
            datatime_time = datetime.datetime.strptime(datatime_time, '%Y-%m-%d %H:%M:%S')
            if '货物已交付' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=4)
                return '{}'.format(datatime_)
            elif '已清关放行' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=6)
                return '{}'.format(datatime_)
            elif '航班已抵达' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=7)
                return '{}'.format(datatime_)
            elif '航班已起飞' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=9)
                return '{}'.format(datatime_)
            elif '已发出' in datas:
                datatime_ = datatime_time + datetime.timedelta(days=10)
                return '{}'.format(datatime_)
            else:
                return None

    def get_week_day(self, dates):

        week_day_dict = {
            0: '星期一',
            1: '星期二',
            2: '星期三',
            3: '星期四',
            4: '星期五',
            5: '星期六',
            6: '星期天',
        }
        day = dates.weekday()
        # print(week_day_dict[day])
        return week_day_dict[day]

    def day_(self, actual_deliver_time):
        dates = datetime.datetime.strptime(str(actual_deliver_time), '%Y-%m-%d %H:%M:%S')
        days = self.get_week_day(dates)
        # add = None
        if days == '星期一':
            add = 9
            return datetime.timedelta(9) + dates
        elif days == '星期二':
            add = 8
            return datetime.timedelta(8) + dates
        elif days == '星期三':
            add = 7
            return datetime.timedelta(7) + dates
        elif days == '星期四':
            add = 6
            return datetime.timedelta(6) + dates
        elif days == '星期五':
            add = 5
            return datetime.timedelta(5) + dates
        elif days == '星期六':
            add = 4
            return datetime.timedelta(4) + dates


if __name__ == '__main__':
    # screening_load是该文件的主函数
    run = Load()

    # run.return_mysql()
    run.screening_load()
